import { request } from '@/utils/request'
import type { ApiResponse, PaginatedResponse } from '@/types/api'
import type { AxiosResponse } from 'axios'

// 统一的API响应处理辅助函数
const handleApiResponse = <T>(response: any): ApiResponse<T> => {
  if (response.data?.success === false) {
    throw new Error(response.data.message || 'API request failed')
  }
  return response.data
}

const extractResponseData = <T>(response: any): T => {
  const apiResponse = handleApiResponse<T>(response)
  if (apiResponse.data === undefined || apiResponse.data === null) {
    throw new Error('Response data is empty')
  }
  return apiResponse.data as T
}

// 缺陷接口
export interface Defect {
  id: string
  title: string
  description?: string
  type: DefectType
  status: DefectStatus
  priority: DefectPriority | 'medium'
  severity: DefectSeverity | 'minor'
  source: DefectSource | 'testing'
  project_id?: string
  project_name?: string
  requirement_id?: string
  requirement_name?: string
  assignee_id?: string
  assignee_name?: string
  reporter_id?: string
  reporter_name?: string
  verifier_id?: string
  verifier_name?: string
  steps_to_reproduce?: string
  expected_result?: string
  actual_result?: string
  environment_info?: DefectEnvironmentInfo
  found_date?: string
  resolved_date?: string
  verified_date?: string
  completed_at?: string
  actual_completed_at?: string
  tags: string[]
  organization_id?: string
  comments: DefectComment[]
  attachments: DefectAttachment[]
  created_by: string
  created_at: string
  updated_at: string
  comment_count: number
  attachment_count: number
  version_id?: string
  version_name?: string
  version_number?: string
  versions?: Array<{
    id: string
    name?: string
    version_number?: string
  }>
}

// 缺陷状态类型（动态状态，从状态管理系统获取）
export type DefectStatus = string
export type DefectPriority = 'lowest' | 'low' | 'medium' | 'high' | 'urgent' | 'critical' | 'blocker'
export type DefectSeverity = 'trivial' | 'minor' | 'major' | 'important' | 'critical' | 'urgent' | 'blocker'
export type DefectType = 'functional' | 'ui' | 'performance' | 'security' | 'compatibility' | 'usability' | 'data' | 'integration' | 'configuration' | 'documentation'
export type DefectSource = 'testing' | 'production' | 'code_review' | 'user_feedback' | 'monitoring' | 'internal' | 'external'

export interface DefectEnvironmentInfo {
  os?: string
  browser?: string
  version?: string
  device?: string
  resolution?: string
  additional_info?: Record<string, any>
}

export interface DefectComment {
  id: string
  content: string
  author_id: string
  author_name?: string
  author_avatar?: string
  parent_comment_id?: string | null
  is_deleted?: boolean
  created_at: string
  updated_at?: string
}

export interface DefectAttachment {
  id: string
  filename: string
  file_path: string
  file_size: number
  content_type: string
  uploaded_by: string
  uploaded_at: string
}

export interface DefectCreate {
  title: string
  description?: string
  type: DefectType
  status?: DefectStatus
  priority?: DefectPriority
  severity?: DefectSeverity
  source: DefectSource
  project_id?: string
  requirement_id?: string
  assignee_id?: string
  reporter_id?: string
  verifier_id?: string
  steps_to_reproduce?: string
  expected_result?: string
  actual_result?: string
  environment_info?: DefectEnvironmentInfo
  found_date?: string
  completed_at?: string
  actual_completed_at?: string
  tags?: string[]
}

export interface DefectUpdate {
  title?: string
  description?: string
  type?: DefectType
  status?: DefectStatus
  priority?: DefectPriority
  severity?: DefectSeverity
  source?: DefectSource
  project_id?: string
  requirement_id?: string
  assignee_id?: string
  reporter_id?: string
  verifier_id?: string
  steps_to_reproduce?: string
  expected_result?: string
  actual_result?: string
  environment_info?: DefectEnvironmentInfo
  found_date?: string
  resolved_date?: string
  verified_date?: string
  completed_at?: string
  actual_completed_at?: string
  tags?: string[]
}

export interface DefectFilter {
  search?: string
  project_id?: string
  requirement_id?: string
  assignee_id?: string
  reporter_id?: string
  status?: DefectStatus
  priority?: DefectPriority
  severity?: DefectSeverity
  defect_type?: DefectType
  source?: DefectSource
  version?: string
  version_id?: string
  found_date_start?: string
  found_date_end?: string
  tags?: string[]
  page?: number
  size?: number
  sort_by?: string
  sort_order?: 'asc' | 'desc'
}

export interface DefectStats {
  total_defects: number
  defects_by_status: Record<string, number>
  defects_by_priority: Record<string, number>
  defects_by_severity: Record<string, number>
  defects_by_type: Record<string, number>
  defects_by_source: Record<string, number>
}

// API 函数 - 返回统一的API响应格式
export const getDefects = async (params?: DefectFilter): Promise<{
  items: Defect[]
  total: number
  page: number
  size: number
}> => {
  // 转换参数：将 page/size 转换为 skip/limit
  const requestParams: any = {}
  if (params) {
    const page = params.page || 1
    const size = params.size || 20
    requestParams.skip = (page - 1) * size
    requestParams.limit = size
    
    // 复制其他参数，确保空字符串转换为undefined
    if (params.search !== undefined && params.search !== null && params.search !== '') {
      requestParams.search = params.search.trim()
    }
    if (params.project_id !== undefined && params.project_id !== null && params.project_id !== '') {
      requestParams.project_id = params.project_id
    }
    if (params.assignee_id !== undefined && params.assignee_id !== null && params.assignee_id !== '') {
      requestParams.assignee_id = params.assignee_id
    }
    if (params.reporter_id !== undefined && params.reporter_id !== null && params.reporter_id !== '') {
      requestParams.reporter_id = params.reporter_id
    }
    if (params.status !== undefined && params.status !== null) {
      requestParams.status = params.status
    }
    if (params.priority !== undefined && params.priority !== null) {
      requestParams.priority = params.priority
    }
    if (params.severity !== undefined && params.severity !== null) {
      requestParams.severity = params.severity
    }
    if (params.defect_type !== undefined && params.defect_type !== null) {
      requestParams.defect_type = params.defect_type
    }
    if (params.source !== undefined && params.source !== null) {
      requestParams.source = params.source
    }
    if (params.version !== undefined && params.version !== null && params.version !== '') {
      requestParams.version = params.version
    }
    if (params.version_id !== undefined && params.version_id !== null && params.version_id !== '') {
      requestParams.version_id = params.version_id
    }
    if (params.found_date_start !== undefined && params.found_date_start !== null && params.found_date_start !== '') {
      requestParams.found_date_start = params.found_date_start
    }
    if (params.found_date_end !== undefined && params.found_date_end !== null && params.found_date_end !== '') {
      requestParams.found_date_end = params.found_date_end
    }
    if (params.tags && Array.isArray(params.tags) && params.tags.length > 0) {
      requestParams.tags = params.tags.join(',')
    }
    if (params.sort_by !== undefined && params.sort_by !== null && params.sort_by !== '') {
      requestParams.sort_by = params.sort_by
    }
    if (params.sort_order !== undefined && params.sort_order !== null) {
      requestParams.sort_order = params.sort_order
    }
  }
  
  const response = await request.get('/defects/', { params: requestParams })
  
  // 处理后端统一响应格式
  // 后端paginated_response返回格式：{success: true, data: [...], pagination: {...}}
  if (response.data && response.data.success) {
    const data = response.data.data
    const pagination = response.data.pagination // pagination在响应数据的顶级
    
    // 后端返回的是数组格式，pagination是顶级字段
    if (Array.isArray(data) && pagination) {
      return {
        items: data.map((defect: any) => ({
          ...defect,
          id: defect.id || defect._id,
          assignee_name: defect.assignee_name || defect.assignee?.name || defect.assignee?.username,
          reporter_name: defect.reporter_name || defect.reporter?.name || defect.reporter?.username,
          project_name: defect.project_name || defect.project?.name,
          version_id: defect.version_id,
          version_name: defect.version_name,
          version_number: defect.version_number
        })),
        total: pagination.total || 0,
        page: pagination.page || 1,
        size: pagination.size || (params?.size || 20)
      }
    }
  }
  
  // 如果响应格式不符合预期，返回空数组并记录警告
  console.warn('Unexpected defect list response format:', response.data)
  return {
    items: [],
    total: 0,
    page: params?.page || 1,
    size: params?.size || 20
  }
}

export const getDefectById = async (id: string): Promise<ApiResponse<Defect>> => {
  const response = await request.get(`/defects/${id}`)
  return handleApiResponse<Defect>(response)
}

export const createDefect = async (data: DefectCreate): Promise<ApiResponse<Defect>> => {
  const response = await request.post('/defects/', data)
  return handleApiResponse<Defect>(response)
}

export const updateDefect = async (id: string, data: DefectUpdate): Promise<ApiResponse<Defect>> => {
  const response = await request.put(`/defects/${id}`, data)
  return handleApiResponse<Defect>(response)
}

export const deleteDefect = async (id: string): Promise<ApiResponse<null>> => {
  const response = await request.delete(`/defects/${id}`)
  return handleApiResponse<null>(response)
}

export const getDefectsByProject = async (projectId: string, params?: DefectFilter): Promise<PaginatedResponse<Defect>> => {
  const response = await request.get('/defects/', { 
    params: { 
      ...params, 
      project_id: projectId 
    } 
  })
  return extractResponseData<PaginatedResponse<Defect>>(response)
}

// 获取与指定需求相关的缺陷列表
export const getDefectsByRequirementId = async (requirementId: string, params?: Omit<DefectFilter, 'requirement_id'>) => {
  const response = await request.get('/defects/', { 
    params: { 
      requirement_id: requirementId, 
      ...params 
    } 
  })
  return response.data
}

// 批量更新缺陷的需求关联
export const batchUpdateDefectsRequirement = async (defectIds: string[], requirementId: string | null) => {
  // 使用批量更新接口来更新 requirement_id
  const response = await request.patch('/defects/batch', {
    defect_ids: defectIds,
    requirement_id: requirementId
  })
  return handleApiResponse(response)
}

export const getDefectStats = async (params?: { project_id?: string }): Promise<ApiResponse<DefectStats>> => {
  const response = await request.get('/defects/stats/', { params })
  return handleApiResponse<DefectStats>(response)
}

export const updateDefectStatus = async (id: string, status: DefectStatus): Promise<ApiResponse<Defect>> => {
  const response = await request.patch(`/defects/${id}/status`, { status })
  return handleApiResponse<Defect>(response)
}

export const updateDefectAssignee = async (id: string, assignee_id?: string): Promise<ApiResponse<Defect>> => {
  const response = await request.patch(`/defects/${id}/assignee`, { assignee_id })
  return handleApiResponse<Defect>(response)
}

export const addDefectComment = async (id: string, content: string, parentCommentId?: string | null): Promise<ApiResponse<DefectComment>> => {
  const response = await request.post(`/defects/${id}/comments`, { content, parent_comment_id: parentCommentId })
  return handleApiResponse<DefectComment>(response)
}

export const updateDefectComment = async (defectId: string, commentId: string, data: { content?: string; is_deleted?: boolean }): Promise<ApiResponse<DefectComment>> => {
  const response = await request.put(`/defects/${defectId}/comments/${commentId}`, data)
  return handleApiResponse<DefectComment>(response)
}

export const deleteDefectComment = async (defectId: string, commentId: string): Promise<ApiResponse<null>> => {
  const response = await request.put(`/defects/${defectId}/comments/${commentId}`, { is_deleted: true })
  return handleApiResponse<null>(response)
}

export const uploadDefectAttachment = async (id: string, file: File): Promise<ApiResponse<DefectAttachment>> => {
  const formData = new FormData()
  formData.append('file', file)
  const response = await request.post(`/defects/${id}/attachments`, formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  return handleApiResponse<DefectAttachment>(response)
}

export const deleteDefectAttachment = async (defectId: string, attachmentId: string): Promise<ApiResponse<null>> => {
  const response = await request.delete(`/defects/${defectId}/attachments/${attachmentId}`)
  return handleApiResponse<null>(response)
}

// 获取缺陷总数
export const getDefectCount = async (params?: Omit<DefectFilter, 'page' | 'size'>): Promise<ApiResponse<{ total: number }>> => {
  const response = await request.get('/defects/count', { params })
  return handleApiResponse<{ total: number }>(response)
}

// 批量更新缺陷状态
export const batchUpdateDefectStatus = async (defectIds: string[], status: DefectStatus): Promise<ApiResponse<{ updated_count: number; failed_count: number }>> => {
  const response = await request.patch('/defects/batch/status', { defect_ids: defectIds, status })
  return handleApiResponse<{ updated_count: number; failed_count: number }>(response)
}

// 批量分配缺陷
export const batchAssignDefects = async (defectIds: string[], assigneeId: string): Promise<ApiResponse<{ updated_count: number; failed_count: number }>> => {
  const response = await request.patch('/defects/batch/assign', { defect_ids: defectIds, assignee_id: assigneeId })
  return handleApiResponse<{ updated_count: number; failed_count: number }>(response)
}

// 获取缺陷评论
export const getDefectComments = async (defectId: string, page: number = 1, pageSize: number = 20): Promise<ApiResponse<{ items: DefectComment[], total: number, page: number, page_size: number }>> => {
  const response = await request.get(`/defects/${defectId}/comments`, { params: { page, page_size: pageSize } })
  return handleApiResponse<{ items: DefectComment[], total: number, page: number, page_size: number }>(response)
}

// 获取缺陷附件
export const getDefectAttachments = async (defectId: string): Promise<ApiResponse<DefectAttachment[]>> => {
  const response = await request.get(`/defects/${defectId}/attachments`)
  return handleApiResponse<DefectAttachment[]>(response)
}

// 获取缺陷统计信息（带趋势数据）
export const getDefectStatsWithTrend = async (params?: { 
  project_id?: string; 
  date_range?: '7d' | '30d' | '90d' 
}): Promise<ApiResponse<{
  total: number;
  by_status: Record<string, number>;
  by_priority: Record<string, number>;
  by_severity: Record<string, number>;
  trend: Array<{ date: string; created: number; resolved: number }>;
}>> => {
  const response = await request.get('/defects/stats', { params })
  return handleApiResponse<{
    total: number;
    by_status: Record<string, number>;
    by_priority: Record<string, number>;
    by_severity: Record<string, number>;
    trend: Array<{ date: string; created: number; resolved: number }>;
  }>(response)
}

// 获取缺陷模块选项（状态、优先级、标签、严重程度）
export interface DefectOptions {
  status: Array<{ code: string; name: string; color: string; description?: string }>
  priority: Array<{ code: string; name: string; color: string; description?: string; sort_order?: number }>
  severity: Array<{ code: string; name: string; color: string }>
  tags: Array<{ id: string; name: string; color: string; description?: string }>
}

export const getDefectOptions = async (): Promise<ApiResponse<DefectOptions>> => {
  const response = await request.get('/defects/options')
  return handleApiResponse<DefectOptions>(response)
}

// 批量更新缺陷（通用批量更新接口）
export interface DefectBulkUpdate {
  defect_ids: string[]
  status?: DefectStatus
  priority?: DefectPriority
  severity?: DefectSeverity
  type?: DefectType
  source?: DefectSource
  assignee_id?: string | null
  reporter_id?: string | null
  project_id?: string
  requirement_id?: string | null
}

export const batchUpdateDefects = async (data: DefectBulkUpdate): Promise<ApiResponse<{ updated_count: number; failed_count: number }>> => {
  const response = await request.patch('/defects/batch', data)
  return handleApiResponse<{ updated_count: number; failed_count: number }>(response)
}

// 批量删除缺陷
export const batchDeleteDefects = async (ids: string[]): Promise<ApiResponse<void>> => {
  const response = await request.delete('/defects/batch', { data: { defect_ids: ids } })
  return handleApiResponse<void>(response)
}

// 导出缺陷
export const exportDefects = async (params?: DefectFilter): Promise<AxiosResponse<Blob>> => {
  return request.get('/defects/export', { 
    params,
    responseType: 'blob'
  })
}

// 导入缺陷
export const importDefects = async (file: File): Promise<ApiResponse<{ success_count: number; error_count: number; errors: string[] }>> => {
  const formData = new FormData()
  formData.append('file', file)
  return request.post('/defects/import', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// 下载导入模板
export const downloadDefectTemplate = (): Promise<AxiosResponse<Blob>> => {
  return request.get('/defects/export-template', {
    responseType: 'blob'
  })
}

// 导出defectAPI对象以兼容其他文件的导入
export const defectAPI = {
  getDefects,
  getDefectById,
  createDefect,
  updateDefect,
  deleteDefect,
  getDefectsByProject,
  getDefectsByRequirementId,
  batchUpdateDefectsRequirement,
  getDefectStats,
  getDefectCount,
  getDefectStatsWithTrend,
  updateDefectStatus,
  updateDefectAssignee,
  batchUpdateDefectStatus,
  batchAssignDefects,
  batchUpdateDefects,
  batchDeleteDefects,
  addDefectComment,
  updateDefectComment,
  deleteDefectComment,
  uploadDefectAttachment,
  deleteDefectAttachment,
  getDefectComments,
  getDefectAttachments,
  getDefectOptions,
  exportDefects,
  importDefects,
  downloadDefectTemplate
}